$(document).ready(function() {
    remove_product_photo();
    focus_input();
    uploadFile();
    //xu li import file excel product
    $("form.form_upload_file").submit(function() {
        $('#upload_target').unbind().load(function() {
            // get content from hidden iframe
            var body = $('#upload_target').contents().find('body ').html();

            // proof content if there is an error
            if (body.indexOf("uperror") != -1) {
                var error = $('#upload_target').contents().find('p.uperror ').html();
                alert(error);

            }
            else {
                var msg = $('#upload_target').contents().find('p.msg').html();
                alert(msg);

            }
        });

    });
    //chọn cach upload photo
    $('input[name="upload_photo"]').click(function() {
        var choose = $('input[name="upload_photo"]:checked').val();
        if (choose == 1) {
            $('.form_upload_photo').removeClass('hide');
            if (!$('.upload_photo_from_url').hasClass('hide')) {
                $('.upload_photo_from_url').addClass('hide');
            }
        } else {
            $('.upload_photo_from_url').removeClass('hide');
            if (!$('.form_upload_photo').hasClass('hide')) {
                $('.form_upload_photo').addClass('hide');
            }
        }
    });
    //xu li upload main photo từ máy tính
    $("form.form_upload_photo").submit(function() {
        $('#iframe_upload_photo').unbind().load(function() {
            // get content from hidden iframe
            var body = $('#iframe_upload_photo').contents().find('body ').html();
            // proof content if there is an error
            var error = '';
            $('#iframe_upload_photo').contents().find('p.uperror ').each(function(index, value) {
                error += '<p style="color:red">' + $(this).html() + '</p>';
            });
            $('#show_error_upload').html(error);
            var folder_temp = $('#iframe_upload_photo').contents().find('p.folder_temp').html();
            $("#folder_temp").val(folder_temp);
            var array_photo_list = new Array();
            $('#iframe_upload_photo').contents().find('p.file_name_temp').each(function(index, value) {
                array_photo_list[array_photo_list.length] = $(this).html();//add photo vao list
            });
            var array_new_photo_thumb = new Array();
            $('#iframe_upload_photo').contents().find('p.thumb_url').each(function(index, value) {
                array_new_photo_thumb[array_new_photo_thumb.length] = $(this).html();//luu anh thumb moi upload
            });
            if (array_new_photo_thumb.length > 0) {
                var html = '';
                for (i = 0; i < array_new_photo_thumb.length; i++) {

                    html += '<tr class="tr_product_photo">';
                    if (i == 0 && !has_main_photo()) {
                        html += '<td><label class="radio"><div class="radio"><span class="checked"><input class="is_main_photo" type="radio" name="is_main_photo" value="' + i + '" style="opacity: 0;" checked></span></div></label></td>';
                    } else {
                        html += '<td> <label class="radio"><div class="radio"><span class=""><input class="is_main_photo" type="radio" name="is_main_photo" value="' + i + '" style="opacity: 0;"></span></div></label></td>';
                    }
                    html += '<td><a href="#"><img src="' + array_new_photo_thumb[i] + '"></a> <input type="hidden" value="' + array_photo_list[i] + '" class="array_photo_list"/></td>';
                    html += '<td><input class="color_name" type="text" name="color_name" value=""></td>';
                    html += '<td><a href="javascript:void(0)" class="btn btn-danger delete_product_photo" ><i class="icon-trash icon-white"></i>Delete</a></td>';
                    html += '</tr>';
                }
                $('#table_upload_photo_list').removeClass('hide').append(html);
                remove_product_photo();
                focus_input();
                $("input:checkbox, input:radio, input:file").uniform();
            }


        });
    });

    //upload main photo từ url
    var upload_photo = false;
    $('#btn_upload_main_photo').click(function(e) {
        if (upload_photo === false) {
            upload_photo = true;
            if ($("#url_main_photo").val() != "") {
                $.post("ajax/uploadProductPhoto.php", {
                    product_photo: encodeURIComponent($("#url_main_photo").val())
                }, function(res) {
                    if (res.type == 0) {
                        $("#folder_temp").val(res.folder_temp);
                        html = '<tr class="tr_product_photo">';
                        if (!has_main_photo()) {
                            html += '<td><label class="radio"><div class="radio"><span class="checked"><input class="is_main_photo" type="radio" name="is_main_photo" value="0" style="opacity: 0;" checked></span></div></label></td>';
                        } else {
                            html += '<td> <label class="radio"><div class="radio"><span class=""><input class="is_main_photo" type="radio" name="is_main_photo" value="0" style="opacity: 0;"></span></div></label></td>';
                        }
                        html += '<td><a href="#"><img src="' + res.thumb_url + '"></a><input type="hidden" value="' + res.file_name_temp + '" class="array_photo_list"/></td>';
                        html += '<td><input class="color_name" type="text" name="color_name" value=""></td>';
                        html += '<td><a href="javascript:void(0)" class="btn btn-danger delete_product_photo" ><i class="icon-trash icon-white"></i>Delete</a></td>';
                        html += '</tr>';
                        $('#table_upload_photo_list').removeClass('hide').append(html);
                        $("#url_main_photo").val("Điền link tải ảnh");
                        remove_product_photo();
                        focus_input();
                        $("input:checkbox, input:radio, input:file").uniform();
                    } else {
                        alert(res.msg);

                    }
                    upload_photo = false;
                }, "json");
            } else {
                alert("Vui lòng điền link photo");

                upload_photo = false;
            }
        }
    });
    //delete extra photo
    $(".btn_delete_extra_photo").click(function() {
        var photo_name = $(this).attr("rel");
        index = array_extra_photo_name.indexOf(photo_name);
        array_extra_photo_name.splice(index, 1);
        $(this).parent().parent().remove();
    });
    //save product
    var act_submit = false;
    $("#save_product").click(function() {
        if (act_submit === false) {
            act_submit = true;
            if (checkValidate("#alert-error-product")) {
                var array_photo_color = new Array();
                var array_is_main_photo = new Array();
                var array_photo_list = new Array();
                $('.array_photo_list').each(function(index, value) {
                     array_photo_list[array_photo_list.length] = $(this).val();
                });
                $('.color_name').each(function(index, value) {
                    array_photo_color[array_photo_color.length] = $(this).val();
                });
                $('.is_main_photo').each(function(index, value) {
                    if ($(this).prop("checked")) {
                        array_is_main_photo[array_is_main_photo.length] = 1;
                    } else {
                        array_is_main_photo[array_is_main_photo.length] = 0;
                    }
                });
                $.post("ajax/updateProduct.php", {
                    product_id: $("#product_id").val(),
                    product_name: $("#product_name").val(),
                    product_code: $("#product_code").val(),
                    link_web: $("#link_web").val(),
                    product_price: $("#product_price").val(),
                    store_price: $("#store_price").val(),
                    stamp_price: $("#stamp_price").val(),
                    product_size: $("#product_size").val(),
                    //manufacture: $("#manufacture").val(),
                    product_category: $("#product_category").val(),
                    folder_temp: $("#folder_temp").val(),
                    array_photo_list: array_photo_list,
                    array_photo_color: array_photo_color,
                    array_is_main_photo: array_is_main_photo,
                    description: $("#description").val()
                }, function(res) {
                    act_submit = false;
                    if (res.type == 0) {
                        alert(res.msg);
                        if ($("#product_id").val() > 0) {
                            window.location = "productList.php";
                        } else {
                            refresh_form();
                        }
                    } else {
                        $("#alert-error-product").html(res.msg).show();
                        hideError("#alert-error-product");
                    }
                }, "json");

            } else {
                act_submit = false;
                return false;
            }
        } else {
            return false;
        }
    });
    //get product info by code
    var get_product_info = false;
    $("#get_product_info_by_code").click(function() {
        if (get_product_info === false) {
            get_product_info = true;
            if ($('#product_code').val() !== "") {
                getProductInfoByCode($('#product_code').val());
                get_product_info = false;
            } else {
                $("#alert-error-product_code").html("Vui lòng điền mã sản phẩm!").show();
                hideError("#alert-error-product");
                get_product_info = false;
            }
        } else {
            return false;
        }
    });
});
function has_main_photo() {
    var has_main_photo = false;
    $('.is_main_photo').each(function(index, value) {
        if ($(this).prop("checked")) {
            has_main_photo = true;
            return false;
        }
    });
    return has_main_photo;
}
function getProductInfoByCode(code) {
    $.post("ajax/getProductInfoByCode.php", {
        product_code: code
    }, function(res) {
        if (res.type == 0) {
            $("#alert-error-product_code").html("Mã sản phẩm đã tồn tại, vui lòng nhập mã khác!").show();
            hideError("#alert-error-product");
        } else {
            $("#alert-error-product_code").html("Mã sản phẩm hợp lệ!").show();
            hideError("#alert-error-product");
        }

    }, "json");
}
function uploadFile() {
    $("#product_photo").change(function() {

        $("#form_upload_photo").submit();
    });
}
function focus_input() {
    $('input[type="text"]').focus(function() {
        $(this).css("color", "#555555");
        $(this).css("border", "1px solid #CCCCCC");
        this.select();
    }).blur(function() {
        if (jQuery.trim(this.value) == '') {
            this.value = (this.defaultValue ? this.defaultValue : '');

        }
    });
}
function remove_product_photo() {
    $('.delete_product_photo').click(function() {
        $(this).parent().parent().remove();
    });
}
function checkValidate(id_append) {
    var emailRegex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i,
            numericRegex = /^[0-9-]+$/;
    var check_char = /^[a-zA-Z]+$/;
    var msgEr = '';
    var valueStr = '';
//    if ($("#product_name").val() == '') {
//        $(id_append).html("Vui lòng nhập tên sản phẩm!").show();
//        actHideError(id_append, $("#product_name"));
//        return false;
//    }
    if ($("#product_code").val() == '') {
        $(id_append).html("Vui lòng nhập mã sản phẩm!").show();
        actHideError(id_append, $("#product_code"));
        return false;
    }
    //if ($("#manufacture").val() == '') {
    //    $(id_append).html("Vui lòng nhập thương hiệu!").show();
    //    actHideError(id_append, $("#manufacture"));
    //    return false;
    //}
    if ($("#product_category").val() == '') {
        $(id_append).html("Vui lòng nhập loại sản phẩm!").show();
        hideError(id_append);
        return false;
    }
    var count_photo = 0;
    $('.array_photo_list').each(function(index, value) {
        count_photo++;
    });
    if (count_photo == 0) {
        $(id_append).html("Vui lòng upload ảnh cho sản phẩm!").show();
        hideError(id_append);
        return false;
    }
    //kiem tra anh dai dien
    //check exist main photo
    if (!has_main_photo()) {
        $(id_append).html("Vui lòng chọn một ảnh làm ảnh đại diện!").show();
        hideError(id_append);
        return false;
    }
    var array_color_name = new Array();
    var result = true;
    $('.color_name').each(function(index, value) {
        if ($(this).val() != '') {
            if (array_color_name.indexOf($(this).val()) >= 0) {
                $(id_append).html("Màu sản phẩm này đã có, vui lòng điền màu khác!").show();
                hideError(id_append);
                $(this).css("border", "1px solid #FF0000");
                result = false;
                return false;
            } else {
                array_color_name[array_color_name.length] = $(this).val();
            }
        } else {
            $(id_append).html("Vui lòng nhập màu sản phẩm ở ô còn trống!").show();
            hideError(id_append);
            $(this).css("border", "1px solid #FF0000");
            result = false;
            return false;
        }
    });


    return result;
}
function refresh_form() {
    $("#product_id").val(0);
    $("#product_name").val('');
    $("#product_code").val('');
    $("#link_web").val('');
    $("#product_price").val('');
    $("#store_price").val('');
    $("#stamp_price").val('');
    $("#product_size").val('');
    $("#product_color").val('');
    // $("#manufacture").val('');
    //$("#product_category").val(0);
    $("#folder_temp").val('');
    $("#url_main_photo").val('');
    $(".filename", "#form_upload_photo").html("No file selected");
    $(".tr_product_photo", "#table_upload_photo_list").remove();
    $("#table_upload_photo_list").addClass('hide');
    $("#description").val('');
    $("iframe", ".cleditorMain").contents().find("body").empty();
}

